package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.FileMapper;
import com.itheima.dao.PictureMapper;
import com.itheima.dao.PictureSortMapper;
import com.itheima.pojo.File;
import com.itheima.pojo.Picture;
import com.itheima.pojo.PictureSort;
import com.itheima.service.PictureService;
import com.itheima.utils.IdWorker;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class PictureServiceImpl implements PictureService {

    @Resource
    private PictureMapper pictureMapper;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private PictureSortMapper pictureSortMapper;

    @Resource
    private IdWorker idWorker;

    /**
     * 增加图片
     *
     * @Param Picture
     */
    @Override
    public Integer add(Picture picture) {
        picture.setUid(String.valueOf(idWorker.nextId()));
        picture.setCreateTime(new Date());
        picture.setUpdateTime(new Date());
        return pictureMapper.insertSelective(picture);
    }

    /**
     * 删除图片
     *
     * @Param Picture
     */
    @Override
    public Integer delete(Picture picture) {
        return pictureMapper.deleteByPrimaryKey(picture);
    }

    /**
     * 编辑图片
     *
     * @Param Picture
     */
    @Override
    public Integer edit(Picture picture) {
        picture.setUpdateTime(new Date());
        return pictureMapper.updateByPrimaryKeySelective(picture);
    }

    /**
     * 获取图片列表
     *
     * @Param Picture
     */
    @Override
    public Page<Picture> getList(Picture picture) {
        PageHelper.startPage(picture.getCurrentPage(),picture.getPageSize());
        List<Picture> pictureList = pictureMapper.select(picture);
        if(pictureList != null && pictureList.size() > 0){
            for (Picture picture1 : pictureList) {
                File file = fileMapper.selectByPrimaryKey(picture1.getFileUid());
                if(file != null) {
                    String picUrl = file.getPicUrl();
                    if(picUrl.startsWith("/blog")){
                        picUrl = "http://qf01xhkh2.hn-bkt.clouddn.com/"+picUrl;
                    }
                    picture1.setPictureUrl(picUrl);
                }
            }
        }
        return (Page<Picture>)pictureList;
    }

    /**
     * 通过图片Uid将图片设为封面
     *
     * @Param Picture
     */
    @Override
    public Integer setCover(Picture picture) {
        Picture picture1 = pictureMapper.selectByPrimaryKey(picture.getUid());

        PictureSort pictureSort = pictureSortMapper.selectByPrimaryKey(picture.getPictureSortUid());
        pictureSort.setFileUid(picture1.getFileUid());
        pictureSort.setUpdateTime(new Date());

        return pictureSortMapper.updateByPrimaryKey(pictureSort);

    }

}
